<!--
 * @Author: hucc
 * @Date: 2021-10-15 16:35:20
 * @LastEditors: hucc
 * @LastEditTime: 2021-10-16 21:02:29
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/axios.js"></script>
    <script>
        //1.设置全局默认配置
        axios.defaults.baseURL = "http://39.103.202.53:8888"
            //2.设置请求拦截器  interceptors 拦截器
        axios.interceptors.request.use(config => {
            //console.log(config);
            //获取token
            const token = sessionStorage.getItem('token')
                //判断请求目标路径只要不是登录接口并且获取的token有值时
            if (config.url != '/user/login' && token) {
                //把token设置到本次请求的请求头里
                config.headers['Authorization'] = token;
            }
            return config
        }, err => {
            return Promise.reject(config);
        });
        //3.设置响应拦截器
        axios.interceptors.response.use(response => {
            // Do something before response is sent
            //将响应拦截下来 自定义内容后再返回   使获取数据时更加简单，不用嵌套那么多
            console.log('重构之前', response);
            response = {
                ...response, //通过...拓展运算符进行剥离response里面的内容 里面有data 
                data: response.data.data, //后面又重写data 所以覆盖了前面的 现在data是重构之后的data
                statusText: response.data.message
            }
            return response;
        }, error => {
            // Do something with response error
            return Promise.reject(error);
        });
        //4.发送请求
        axios.post('/user/login', {
            username: 'admin1',
            password: '123321'
        }).then(res => {
            console.log('重构之后', res);
            sessionStorage.setItem('token', res.data.token);
        })
        axios.post('/user/info', {
            username: 'admin1',
            password: '123321'
        }).then(res => {
            // sessionStorage.setItem('token', res.data.data.token);
        })
    </script>
</head>

<body>

</body>

</html>